/**
 * 
 */
package com.bluestone.core;

import java.awt.Rectangle;
import java.awt.image.BufferedImage;

import com.bluestone.util.Util;

/**
 * CheckRGBAction can check where some area pixel change or not.
 * @author <a href="mailto:ming7655@gmail.com">Aaron</a>
 */
public class CheckRGBAction extends Action {
	private BufferedImage oldBI = null;

	private Rectangle rectangle = null;

	/**
	 * 
	 * @param type String that defines the type of the action.
	 * @param target String that defines the graphical elements operated by action.
	 * @param value String that defines the retangle(x,y,width,height) of the ara,for example:value="5,5,10,10"
	 * @param delay String that defines the delay time after the action finished.
	 * @param offset String that defines the offset of the graphical elements.
	 */
	public CheckRGBAction(String type, String target, String value,
			String delay, String offset) {
		super(type, target, value, delay, offset);
	}

	/**
	 * Check the pixel of the area of retangle(x,y,width,height) change or not in the timeout.
	 * @return true if the pixel of the area changed.
	 */
	@Override
	public boolean execute() {
		if (!super.execute()){
			return false;
		}
		if (value != null) {
			String[] values = value.split(",");
			if (values == null || values.length != 4) {
				return false;
			}
			int x = Integer.parseInt(values[0]);
			int y = Integer.parseInt(values[1]);
			int width = Integer.parseInt(values[2]);
			int height = Integer.parseInt(values[3]);
			rectangle = new Rectangle(x, y, width, height);
			oldBI = robot.createScreenCapture(rectangle);
			long start = System.currentTimeMillis();
			boolean isEquealed = true;
			long end = System.currentTimeMillis();
			long counts = end - start;
			if (this.getTimeout() != null) {
				long time = Long.valueOf(this.timeout).longValue();
				while (isEquealed && counts < time) {
					robot.delay(Util.getDelayTime(Util.DELAY500));
					isEquealed = isEquealed(oldBI);
					end = System.currentTimeMillis();
					counts = end-start;
				}
			}
			if (delay != null) {
				robot.delay(Util.getDelayTime(Integer.parseInt(delay)));
			} else {
				robot.delay(Util.getDelayTime(Util.CHECKDELAY));
			}
			return !isEquealed;
		}
		return false;
	}

	private boolean isEquealed(BufferedImage oldBI) {
		BufferedImage newBI = robot.createScreenCapture(this.rectangle);
		return Util.compareBufferedImage(oldBI, newBI);
	}

}
